# -*- coding: utf-8 -*-
'''Wrapper module for the Tk treectrl widget.'''
# TODO:
# - methods that need to be fixed:
#      item_sort(): should accept multiple sets of arguments
#      itemstate_forcolumn(): should it be possible to pass further options?
#      itemstate_set(): see function comments
#      notify_generate() and notify_install()
#      the marquee_ methods need to be tested

# Stand (6.7.12): 2.2.10 ist komplett
#                 2.3 - 2.3.2  ist komplett, weiter gehts mit 2.4
#                       aber erst gradient_xxx testen!!
#                 2.4   events + elements sind fertig -> testen
#                        - weiter mit header methoden

try:
    import tkinter
except ImportError:
    import Tkinter as tkinter

class TreectrlEvent:
    '''Container for the properties of an event.
    This is very similar to a tkinter.Event, except that it holds a different
    set of attributes. Instances of this type are generated if one of the
    static or dynamic treectrl events occurs.

    Static, i.e. installed into the widget by default, events include:

    <ActiveItem>: Generated whenever the active item changes.
    <Collapse-before>: Generated before an item is collapsed.
    <Collapse-after>: Generated after an item is collapsed.
    <Expand-before>: Generated before an item is expanded. This event is useful
                     if you want to add child items to the item just before the
                     item is expanded.
    <Expand-after>: Generated after an item is expanded.
    <ItemDelete>: Generated when items are about to be deleted by the
                  item_delete() command.
    <ItemVisibility>: Generated when items become visible on screen and when
                      items are no longer visible on screen. This event is
                      useful if you have a very large number of items and want
                      to assign styles only when items are actually going to be
                      displayed.
    <Scroll-x>: Generated whenever the view in the treectrl changes in such a
                way that a horizontal scrollbar should be redisplayed.
    <Scroll-y>: Generated whenever the view in the treectrl changes in such a
                way that a vertical scrollbar should be redisplayed.
    <Selection>: Generated whenever the selection changes. This event gives
                 information about how the selection changed.

    In addition to the pre-defined static events such as <ActiveItem> and
    <Selection>, new dynamic events can be created by using the
    notify_install() command.
    The following events may be generated by the library scripts:

    <ColumnDrag-begin>
    <ColumnDrag-receive>
    <ColumnDrag-end>: Generated whenever the user drag-and-drops a column
                      header. The library scripts do not actually move a
                      dragged column. You must bind to the receive event to
                      move the column.
    <ColumnDrag-indicator>: generated whenever the place to drop a dragged
                            column header is updated.
    <Drag-begin>
    <Drag-receive>
    <Drag-end>: Generated whenever the user drag-and-drops a file into a
                directory. This event is generated by the filelist-bindings.tcl
                library code, which is not used by default.
    <Edit-begin>
    <Edit-accept>
    <Edit-end>: The filelist-bindings.tcl code will display a text-editing
                window if the user clicks on a selected file/folder name.
    <Header-invoke>: Generated whenever the user clicks and releases the left
                     mouse button in a column header if the column's -button
                     option is true.
                     You can bind a callback to this event to sort the list.
    <Header-state>: generated whenever the state of an individual column
                    header is changed during mouse-pointer events.

    If a callback function for one of these events is registered using
    notify_bind(), the callback is called with a TreectrlEvent as first
    argument. It will have the following attributes (in braces are the event
    types for which the attribute is valid):

    detail - the detail name, e.g "after" if the event is "<Expand-after>"
            (all static events).
    name - the event name, e.g "Expand" if the event is "<Expand-after>"
            (all static events).
    pattern - the complete event pattern, either "<name>" or "<name-detail>"
            (all static events).
    object - The object argument to the notify_bind() command
            (all static events).
    widget - The treectrl widget which generated the event (all static events).

    item - The item id (<Collapse>, <Expand>, <Drag>, <Edit> events).

    active - The current active item (<ActiveItem> events).
    prevactive - The previous active item (<ActiveItem> events).

    deleteditems - List of items ids being deleted (<ItemDelete> events).

    visible- List of items ids which are now visible (<ItemVisibility> events).
    nonvisible - List of items ids which are no longer visible
            (<ItemVisibility> events).

    lower - Same as the first fraction appended to -yscrollcommand
            (<Scroll> events).
    upper - Same as the second fraction appended to -yscrollcommand
            (<Scroll> events).

    selectcount - Same as the selection_count() widget command
            (<Selection> events).
    deselected - List of newly-deselected item ids (<Selection> events).
    selected - List of newly-selected item ids (<Selection> events).

    textelement - The name of the edited text element (<Edit> events).
    text - The edited text (<Edit> events).

    column - The column that was dragged or whose header was clicked
             (<ColumnDrag>, <Header-invoke>, <Edit> events).

    columnbefore - The column to move the dragged column before
            (<ColumnDrag> events).

    draggeditems - The list of dragged items (<Drag> events).'''
    pass

class Treectrl(tkinter.Widget):
    '''A treectrl is a widget which displays items in a one- or two-dimensional
    arrangement. Items have a parent-child relationship with other items. Items
    have a set of states, which are boolean properties. Items may be spread
    about one or more columns. For each column of an item there is a style
    associated, which determines how to display the item's column taking into
    account the item's current state set. One column can be defined to display
    the data in a hierarchical structure.
    Normally the origin of the coordinate system is at the upper-left corner of
    the window containing the treectrl. It is possible to adjust the origin of
    the coordinate system relative to the origin of the window using the
    xview() and yview() widget commands; this is typically used for scrolling.
    A treectrl widget can be horizontal or vertical oriented like many other Tk
    widgets. For displaying hierarchical data only vertical orientation is
    useful, since only then the children of an item are displayed directly
    below their parent. If the treectrl widget is used only to display data in
    a multicolumn listbox, the specification of an orientation will give useful
    results.

    STANDARD OPTIONS
    -background
    -borderwidth
    -cursor
    -font
    -highlightbackground
    -highlightcolor
    -highlightthickness
    -orient
    -relief
    -takefocus
    -xscrollcommand
    -yscrollcommand
    -foreground

    WIDGET SPECIFIC OPTIONS
    -backgroundimage
        Specifies the name of an image to draw as the list background. The
        image is tiled horizontally and vertically to fill the content area of
        the list. If the image is transparent it is drawn on top of the
        background color(s).
    -backgroundmode
        Specifies how the background color of items is chosen in each column.
        The value should be one of row, column, order, or ordervisible. The
        default is row. This option has only an effect for columns which have
        -itembackground defined as list of two or more colors (see section
        COLUMNS below for more on this). If row or column is specified, the
        background color is chosen based on the location of the item in the
        1- or 2-dimensional grid of items as layed out on the screen; this
        layout of items is affected by the -orient and -wrap options as well as
        item visibility. When order or ordervisible is specified, the
        background color is chosen based on the result of the item order
        command, regardless of the layout of items.
    -bgimage
        Synonym for -backgroundimage (since 2.3)
    -bgimageanchor
        Controls the alignment of the -backgroundimage.  The value is a
        standard Tk anchor position such as "nw", "se" or "center", etc.
        The image is aligned to the content area when the image doesn't scroll,
        otherwise the image is aligned to the canvas.  The default is "nw".
    -bgimageopaque
        A boolean that indicates whether or not the -backgroundimage is
        partially transparent.  This is needed because there is no way to tell
        in Tk whether an image contains transparency.  The default is True, so
        if you use a transparent -backgroundimage you must set this to False.
    -bgimagescroll
        Controls whether the -backgroundimage scrolls along with the items or
        remains locked in place. The value can be an emptry string for no
        scrolling, "x" for horizontal scrolling only, "y" for vertical
        scrolling only, or "xy" (the default) for scrolling in both directions.
    -bgimagetile
        Controls whether the -backgroundimage is tiled along the x and y axes.
        The value can be "", "x", "y" or "xy" (the default).
    -buttonbitmap
        Specifies the bitmap to be used as the expand/collapse button to the
        left of an item. This is a per-state option. If a bitmap is specified
        for a certain item state, it overrides the effects of -usetheme.
    -buttoncolor
        Specifies the foreground color which should be used for drawing the
        outline and the plus or minus sign of the button to the left of an
        item.
    -buttonimage
        Specifies the image to be used as the expand/collapse button to the
        left of an item. This is a per-state option. If an image is specified
        for a certain item state, it overrides the effects of -buttonbitmap and
        -usetheme.
    -buttonsize
        Specifies the width and height of the button drawn to the left of an
        item in any of the forms acceptable to Tk_GetPixels.
    -buttonthickness
        Specifies the width of the outline and the plus or minus sign of the
        button to the left of an item in any of the forms acceptable to
        Tk_GetPixels.
    -buttontracking
        On Mac OS X and Gtk+ the expand/collapse buttons don't toggle when they
        are clicked, only when the mouse button is released over them, like
        regular pushbuttons.  The value of this option is a boolean; when True
        the buttons toggle when the mouse button is released, when False the
        buttons toggle when clicked.  The default is True on Mac OS X and
        Gtk+, False on Win32 and X11.
    -canvaspadx
    -canvaspady
        These options allow whitespace margins around the edges of the canvas.
        This is useful for 2D views where you don't want the items to butt
        against the window borders.  The value of each option is a list of one
        or two screen distances specifying the width of the left/right margins
        and the height of the top/bottom margins respectively.
    -columnprefix
        Specifies an ascii string that changes the way column ids are reported
        and processed. If this option is a non-empty string, the usual integer
        value of a column id is prefixed with the given string. This can aid
        debugging but it is important your code doesn't assume column ids are
        integers if you use it.
    -columnproxy
        If this option specifies a non empty value, it should be a screen
        distance in any of the forms acceptable to Tk_GetPixels. Then a 1 pixel
        thick vertical line will be drawn at the specified screen distance from
        the left edge of the treectrl widget, which reaches from top to bottom
        of the treectrl widget and uses an inverting color (i.e black on
        lighter background, white on darker background). This line can be used
        to give the user a visual feedback during column resizing.
    -columnresizemode
        Specifies the visual feedback used when resizing columns. The value
        should be one of proxy or realtime. For proxy, a 1-pixel thick vertical
        line is drawn representing where the right edge of the column will be
        after resizing. For realtime, the column's size is changed while the
        user is dragging the right edge of the column.
        Since treectrl-2.3 the default value is "realtime",
        in earlier versions it used to be "proxy".
    -columntagexpr
        Specifies a boolean that enables or disables tag expressions in column
        descriptions.
        When the value of this option is False the characters (', ')', '&',
        '|', '^' and '!' have no special significance when using tags in column
        descriptions. This is useful for applications which may have arbitrary
        tags applied to columns or items.
    -defaultstyle
        Specifies a list of styles, one per column, to apply to each item
        created by the item create command. The number of styles in the list
        can be different from the number of tree columns. Each list element
        should be a valid style name or an empty string to indicate no style
        should be applied to a specific column. The list of styles is updated
        if a style is deleted or if a column is moved.
        This option is deprecated since treectrl-2.2, use
        column_configure(itemstyle=...) instead.
    -doublebuffer
        Specifies if double-buffering should be used to improve displaying. The
        value should be one of none, window, or item. For none no
        double-buffering is used at all, which may be most memory efficient,
        but will probably generate some flickering on the screen. For window
        the complete tree is double-buffered, which requires a buffer big
        enough to contain the complete widget. For item, which is the default,
        every item is separately double-buffered, so it works with a buffer
        size as big as the biggest item.
        This option has no effect since tktreectrl-2.2.10 .
    -headerfont
        This is the font used for drawing text in column headers. The default
        value is TkHeadingFont where that font is defined (usually on Tk 8.5+),
        otherwise it is the default listbox font.  On Mac OS X, TkHeadingFont
        is the small system font used for drawing text in the fixed-height
        headers. This new option results in a different default look to column
        text on X11, where TkHeadingFont is a bold font.
    -headerfg
    -headerforeground
        The foreground text color used when drawing text in column headers.
        On Gtk+, the system theme may override this color.
    -height
        Specifies the desired height for the window in any of the forms
        acceptable to Tk_GetPixels. The default is 200 pixels. If this option
        is less than or equal to zero then the window will not request any
        size at all.
    -indent
        Specifies the amount of indentation in any of the forms acceptable to
        Tk_GetPixels. The default is 19 pixel. Indentation is the screen
        distance an item is displayed more to the right than its father.
    -itemgapx
    -itemgapy
        These options allow whitespace gaps between adjacent items. This is
        useful for 2D views such as an icon view in a file browser or an image
        thumbnail list.  The value of each option is a screen distance
        defaulting to zero.
    -itemheight
        Specifies a fixed height for every item in any of the forms acceptable
        to Tk_GetPixels. If non-zero, this option overrides the requested
        height of an item and the -minitemheight option. The default is 0,
        which means that every item has the height requested by the
        arrangement of elements in each column. Items are never shorter than
        the maximum height of a button.
    -itemprefix
        Specifies an ascii string that changes the way item ids are reported
        and processed. If this option is a non-empty string, the usual integer
        value of an item id is prefixed with the given string. This can aid
        debugging but it is important your code doesn't assume item ids are
        integers if you use it.
    -itemtagexpr
        Specifies a boolean that enables or disables tag expressions in item
        descriptions.
        When the value of this option is False the characters (', ')', '&',
        '|', '^' and '!' have no special significance when using tags in item
        descriptions. This is useful for applications which may have arbitrary
        tags applied to columns or items.
    -itemwidth
        Specifies a fixed width for every item in any of the forms acceptable
        to Tk_GetPixels. If more than one column is visible, then this option
        has no effect. If the -orient option is vertical, and the -wrap
        option is unspecified, then this option has no effect (in that case
        all items are as wide as the column).
    -itemwidthequal
        Specifies a boolean that says whether all items should have the same
        width. If more than one column is visible, then this option has no
        effect. If the -orient option is vertical, and the -wrap option is
        unspecified, then this option has no effect (in that case all items are
        as wide as the column). If the -itemwidth option is specified, then
        this option has no effect.
    -itemwidthmultiple
        Specifies a screen distance that every item's width will be evenly
        divisible by in any of the forms acceptable to Tk_GetPixels. If more
        than one column is visible, then this option has no effect. If the
        -orient option is vertical, and the -wrap option is unspecified, then
        this option has no effect (in that case all items are as wide as the
        column).
        If the -itemwidth option is specified, then this option has no effect.
    -linecolor
        Specifies the color which should be used for drawing the connecting
        lines between related items.
    -linestyle
        Specifies the style of the connecting lines between related items,
        should be dot which is the default, or solid.
    -linethickness
        Specifies the thickness of the connecting lines between related items
        in any of the forms acceptable to Tk_GetPixels.
    -minitemheight
        Specifies a minimum height for every item in any of the forms
        acceptable to Tk_GetPixels. The default is 0, which means that every
        item has the height requested by the arrangement of elements in each
        column. This option has no effect if the -itemheight option is
        specified. Items are never shorter than the maximum height of a button.
    -scrollmargin
        The interpretation of this option is left to Tcl scripts that implement
        scrolling: the widget implementation ignores this option entirely.
        Defaults to 0.
    -selectmode
        Specifies one of several styles for manipulating the selection. The
        value of the option may be arbitrary, but the default bindings expect
        it to be either single, browse, multiple, or extended; the default
        value is browse.
    -showbuttons
        Specifies a boolean value that determines whether this widget displays
        a button to the left of any item. If the button is actually drawn can
        be configured for every item with the item hasbutton widget command,
        but if this option is set to false, the configuration of an item has
        no effect. The default value is True.
    -showheader
        Specifies a boolean value that determines whether this widget should
        display the header line with the column names at the top of the widget.
        The default value is True.
    -showlines
        Specifies a boolean value that determines whether this widget should
        draw the connecting lines between related items.
        In versions prior to trectrl-2.3 the default value was True. Since 2.3
        the default value is False on Mac OS X and Gtk+, True on Win32 and X11.
    -showroot
        Specifies a boolean value that determines whether this widget should
        draw the root item. By suppressing the drawing of the root item the
        widget can have multiple items that appear as toplevel items.
        The default value is True.
    -showrootbutton
        Specifies a boolean value that determines whether this widget should
        draw a button before the root item. The default value is False.
    -showrootchildbuttons
        Specifies a boolean value that determines whether this widget should
        draw the expand/collapse buttons next to children of the root item.
        The default value is True.
    -showrootlines
        Specifies a boolean value that determines whether this widget should
        draw the connecting lines between children of the root item.
        The default value is True.
    -treecolumn
        Specifies a column description that determines which column displays
        the buttons and lines. The default is unspecified.
    -usetheme
        Specifies a boolean value that determines whether this widget should
        draw parts of itself using a platform-specific theme manager.
        Since treectrl-2.3 the default value is now True, in earlier versions
        the default used to be False.
    -width
        Specifies the desired width for the window in any of the forms
        acceptable to Tk_GetPixels. The default is 200 pixels. If this option
        is less than or equal to zero then the window will not request any size
        at all.
    -wrap
        Specifies whether items are arranged in a 1- or 2-dimensional layout.
        If the value is an empty string (the default), then items are arranged
        from top to bottom (orient='vertical') or from left to right (orient=
        'horizontal') in a 1-dimensional layout. If the value is "N items",
        then no more than N items will appear in a vertical group
        (orient='vertical') or horizontal group (orient='horizontal').
        If the value is "N pixels", then no vertical group of items will be
        taller than N pixels (orient='vertical') or no horizontal group of
        items will be wider than N pixels (orient='horizontal').
        If the value is "window", then no vertical group of items will be
        taller than the window (orient='vertical') or no horizontal group of
        items will be wider than the window (orient='horizontal').
    -xscrolldelay
        Specifies the amount of time before the default binding should handle
        repeating mouse motion events in horizontal direction with button 1
        pressed. The value should be a sequence of 1 or 2 integers. The first
        integer specifies the timespan in microseconds before the active item
        should be changed to get nearer to the current mouse position.
        If there are two integers specified, the first is only used for the
        first motion event, any repeating motion events are handled after the
        seconds amount of miliseconds is elapsed.
    -xscrollincrement
        Specifies an increment for horizontal scrolling, in any of the usual
        forms permitted for screen distances. If the value of this option is
        greater than zero, the horizontal view in the window will be
        constrained so that the x coordinate at the left edge of the window
        is always an even multiple of -xscrollincrement; furthermore, the
        units for scrolling (e.g., the change in view when the left and right
        arrows of a scrollbar are selected) will also be -xscrollincrement.
        If the value of this option is less than or equal to zero, then
        horizontal scrolling is unconstrained.
    -xscrollsmoothing
    -yscrollsmoothing
        When these options are set to true and the xview or yview commands are
        called to scroll by "units", scrolling occurs according to the
        -xscrollincrement or -yscrollincrement options, and all other
        scrolling is done as if the -xscrollincrement or -yscrollincrement
        options were set to 1.  The effect is that when dragging the scrollbar
        thumb scrolling is very smooth, but when clicking the scrollbar
        buttons scrolling is done in coarser increments.
    -yscrolldelay
        Specifies the amount of time before the default binding should handle
        repeating mouse motion events in vertical direction with button 1
        pressed. The value should be a list of 1 or 2 integers. The first
        integer specifies the timespan in microseconds before the active item
        should be changed to get nearer to the current mouse position. If there
        are two integers specified, the first is only used for the first motion
        event, any repeating motion events are handled after the seconds amount
        of miliseconds is elapsed.
    -yscrollincrement
        Specifies an increment for vertical scrolling, in any of the usual
        forms permitted for screen distances. If the value of this option is
        greater than zero, the vertical view in the window will be constrained
        so that the y coordinate at the top edge of the window is always an
        even multiple of -yscrollincrement; furthermore, the units for
        scrolling (e.g., the change in view when the top and bottom arrows
        of a scrollbar are selected) will also be -yscrollincrement. If the
        value of this option is less than or equal to zero, then vertical
        scrolling is unconstrained.'''

    TreectrlVersion = None
    _last_element = 0
    _last_gradient = 0
    _last_style = 0

    def __init__(self, master=None, cnf={}, **kw):
        if tkinter._support_default_root:
            if not master:
                if not tkinter._default_root:
                    tkinter._default_root = tkinter.Tk()
                master = tkinter._default_root
        ver = master.tk.call('package', 'require', 'treectrl')
        if not Treectrl.TreectrlVersion:
            Treectrl.TreectrlVersion = ver
        tkinter.Widget.__init__(self, master, 'treectrl', cnf, kw)

    def _configure(self, cmd, cnf, kw):
        """Internal function."""
        # modified version of Tkinter's _configure()
        if kw:
            cnf = tkinter._cnfmerge((cnf, kw))
        elif cnf:
            cnf = tkinter._cnfmerge(cnf)
        if cnf is None:
            cnf = {}
            s = self.tk.split(self.tk.call(tkinter._flatten((self._w, cmd))))
            try:
                for x in s:
                    cnf[x[0][1:]] = (x[0][1:],) + x[1:]
            except TypeError:
                # this happens in notify_configure(), where the output doesn't
                # conform to tk standards; instead of a list of the form:
                # {-data {} {} {} {}} {-datatype {} {} {} {}}} etc.
                # we get a string like: -active 1  there
                s = (s, )
                for x in s:
                    cnf[x[0][1:]] = (x[0][1:],) + x[1:]
            return cnf
        if isinstance(cnf, str):
            x = self.tk.split(self.tk.call(
                                tkinter._flatten((self._w, cmd, '-'+cnf))))
            return (x[0][1:],) + x[1:]
        self.tk.call(tkinter._flatten((self._w, cmd)) + self._options(cnf))

    def _create(self, itemType, args, kw):
        """Internal function."""
        # mainly stolen from tkinter.Canvas
        args = tkinter._flatten(args)
        if args:
            cnf = args[-1]
            if isinstance(cnf, (dict, tuple)):
                args = args[:-1]
            else:
                cnf = {}
        else:
            cnf = {}
        return self.tk.call(self._w, itemType,
                            'create', *(args + self._options(cnf, kw)))

    def _getboolean(self, value):
        '''Simple workaround for tkapp.getboolean() which sometimes returns
        0/1 and sometimes returns True/False.
        This always returns either True or False.'''
        return (self.tk.getboolean(value) and True) or False

    _subst_format_notify = ('%b', '%c', '%d', '%e', '%i', '%h', '%l', '%p',
                            '%t', '%u', '%v', '%C', '%D', '%E', '%H', '%I',
                            '%P', '%S', '%W', '%T')
    _subst_format_str_notify = " ".join(_subst_format_notify)

    def _substitute_notify(self, *args):
        """Internal function."""
        if len(args) != len(self._subst_format_notify):
            return args
        def getint_event(s):
            try:
                return int(s)
            except ValueError:
                return s
        def getints_event(l):
            try:
                return self._getints(l)
            except ValueError:
                return l
        b, c, d, e, i, h, l, p, t, u, v, C, D, E, H, I, P, S, W, T = args
        ev = TreectrlEvent()
        # standard attributes
        ev.detail = d
        ev.name = e
        ev.pattern = P
        # object may be a widget or a column
        try:
            ev.object = self._nametowidget(W)
        except KeyError:
            ev.object = getint_event(W)
        try:
            ev.widget = self._nametowidget(T)
        except KeyError:
            ev.widget = T
        # <Collapse-before>, <Collapse-after>, <Expand-before>,
        # <Expand-after>, <Edit-end>
        ev.item = getint_event(I)
        # <ActiveItem>
        ev.active = getint_event(c)
        ev.prevactive = getint_event(p)
        # <ItemDelete>
        ev.deleteditems = getints_event(i)
        # <ItemVisibility>
        ev.visible = getints_event(v)
        ev.nonvisible = getints_event(h)
        # <Scroll-x>, <Scroll-y>
        ev.lower = l
        ev.upper = u
        # <Selection>
        ev.selectcount = getint_event(c)
        ev.deselected = getints_event(D)
        ev.selected = getints_event(S)
        # <ColumnDrag-end>, <Header-invoke>
        ev.column = getint_event(C)
        # <ColumnDrag-end>
        ev.columnbefore = getint_event(b)
        # <Drag-end>
        ev.draggeditems = getints_event(l)
        # <Edit-end>
        ev.textelement = E
        ev.text = t
        # <ColumnDrag>, <Header>
        ev.header = getint_event(H)
        return (ev,)

    def activate(self, itemDesc):
        '''Sets the active item to the one described by ITEMDESC, and
        switches on the state ACTIVE for this item. From now on the item
        can be retrieved with the item description ACTIVE. An <ActiveItem>
        event is generated.'''
        self.tk.call(self._w, 'activate', itemDesc)

    def bbox(self, area=None):
        '''Returns a list with four elements giving the bounding box (left,
        top, right and bottom) of an area of the window. If AREA is not
        specified, then the result is the bounding box of the entire window.
        If AREA is CONTENT, then the result is the part of the window not
        including borders, headers, or locked columns. If AREA is HEADER, then
        the result is the part of the window not including borders where column
        titles are displayed. If AREA is LEFT, then the result is the part of
        the window not including borders or headers where left-locked columns
        are displayed. If AREA is RIGHT, then the result is the part of the
        window not including borders or headers where right-locked columns are
        displayed. None is returned if the display area has no height or width,
        which can be true for various reasons such as the window is too small,
        or the header is not displayed, or there aren't any locked columns.'''
        return self._getints(self.tk.call(self._w, 'bbox', area))

    def canvasx(self, screenx):
        '''Given a window x-coordinate in the treectrl screenx, this
        command returns the treectrl x-coordinate that is displayed
        at that location.'''
        return int(self.tk.call(self._w, 'canvasx', screenx))

    def canvasy(self, screeny):
        '''Given a window y-coordinate in the treectrl screeny, this
        command returns the treectrl y-coordinate that is displayed
        at that location.'''
        return int(self.tk.call(self._w, 'canvasy', screeny))

    def column_bbox(self, column):
        '''Returns a list with four elements giving the bounding box for the
        column header specified by COLUMN. If the treectrl is configured not to
        display the column headers by means of the showheader option,
        then None is returned instead.'''
        return self._getints(self.tk.call(
                                self._w, 'column', 'bbox', column)) or None

    def column_cget(self, column, option):
        '''This command returns the current value of the option named OPTION
        for the column specified by COLUMN. COLUMN may also be the string TAIL
        to specify the tail column. OPTION may have any of the values accepted
        by the column_configure() widget command.'''
        return self.tk.call(self._w, 'column', 'cget', column, '-'+option)

    def column_configure(self, column, cnf=None, **kw):
        '''This command is similar to the configure() widget command except
        that it modifies options associated with the column specified by COLUMN
        instead of modifying options for the overall treectrl widget. COLUMN
        may be the string TAIL to specify the tail column. If COLUMN is the
        string ALL, at least one option-value pair must be given; in this case
        all the columns are configured.
        Available options are:
            arrow arrowbitmap arrowgravity arrowimage arrowpadx arrowpady
            arrowside background bitmap borderwidth button expand font
            gridleftcolor gridrightcolor image imagepadx imagepady
            itembackground itemjustify itemstyle justify lock maxwidth minwidth
            resize squeeze state stepwidth tags text textcolor textlines
            textpadx textpady uniform visible weight width widthhack'''
        return self._configure(('column', 'configure', column), cnf, kw)
    column_config = column_configure

    def column_compare(self, column1, op, column2):
        '''From both columns the index is retrieved (as returned from the
        column_order() widget command). Then these indexes are compared using
        the operator OP, which must be either <, <=, ==, >=, >, or !=.
        The return value of this command is True if the comparison evaluated to
        true, False otherwise.'''
        return self._getboolean(self.tk.call(
                        self._w, 'column', 'compare', column1, op, column2))

    def column_count(self, *args):
        '''If no additional argument is given, returns an integer giving the
        number of columns created by the column_create() widget command which
        haven't been deleted by the column_delete() widget command. The tail
        column is not counted in this case. If argument(s) are given, the
        result is the number of columns that match the column description.
        For example:
            self.colum_count('visible') will return the number of columns whose
                                        -visible option is True, and:
            self.column_count('tag', 'a^b') will return the number of columns
                                    with either tag "a" or "b", but not both.
        Multiple column descriptions may be combined, like:
            self.column_count('tag', 'foo', 'tag', 'bar', 'visible')'''
        return int(self.tk.call(self._w, 'column', 'count', args or None))

    def column_create(self, *args, **kw):
        '''This command creates a new column in the treectrl widget. The new
        column is placed to the right of all other columns (except the tail
        column). Any option-value arguments configure the new column according
        to the column_configure() command. The return value is the unique
        identifier of the new column.'''
        return int(self._create('column', args, kw))
    create_column = column_create

    def column_delete(self, first, last=None):
        '''Deletes the specified column(s) from the treectrl widget. If either
        FIRST or LAST is specified as ALL, then all columns are deleted. The
        tail column cannot be deleted and it is an error to specify it. The
        order of first and last doesn't matter, and first may be equal to
        last.'''
        self.tk.call(self._w, 'column', 'delete', first, last)
    delete_column = column_delete

    def column_dragcget(self, option):
        return self.tk.call(self._w, 'column', 'dragcget', option)

    def column_dragconfigure(self, cnf=None, **kw):
        '''The user can move a column within a treectrl by drag-and-drop.
        Feedback consists of a semi-transparent photo image of the header of
        the column being dragged and a 2-pixel-thick vertical line to indicate
        where the column may be dropped. The drag image consists of a colored
        background rectangle plus the image and/or text displayed in the column
        header. The 2-pixel-thick line will be drawn over the left edge of the
        column before which the dragged column may be dropped.
        The library scripts generate a <ColumnDrag-accept> event when the user
        has successfully drag-and-drop'd a column. You will have to bind a
        callback to this event if you want to move the dragged column.'''
        return self._configure(('column', 'dragconfigure'), cnf, kw)

    def column_id(self, column):
        '''This command resolves the column description COLUMN into a unique
        column identifier. If the column described by COLUMN doesn't exist,
        this command returns None.'''
        return self.tk.call(self._w, 'column', 'id', column) or None

    def column_list(self, visible=False):
        '''This command returns a list of identifiers for every column (except
        the tail) from left to right. If VISIBLE is True, only columns whose
        visible option is True are returned.'''
        if visible:
            return self.tk.splitlist(self.tk.call(
                                        self._w, 'column', 'list', '-visible'))
        return self.tk.splitlist(self.tk.call(self._w, 'column', 'list'))

    def column_move(self, column, before):
        '''Moves the specified COLUMN to the left of the column specified by
        BEFORE. If BEFORE is the string TAIL, the column COLUMN will become the
        last column.'''
        self.tk.call(self._w, 'column', 'move', column, before)

    def column_neededwidth(self, column):
        '''This command returns an integer giving the needed width of the
        column specified by COLUMN. The needed width is the maximum of the
        width of the column header and the width of the widest currently
        visible item.'''
        return int(self.tk.call(self._w, 'column', 'needewidth', column))

    def column_order(self, column, visible=False):
        '''This command returns an integer giving the position of COLUMN in the
        list of columns starting from zero for the leftmost column. If VISIBLE
        is True, only columns whose visible option is True are considered,
        and -1 is returned if COLUMN's visible option is False.'''
        if visible:
            return int(self.tk.call(
                            self._w, 'column', 'order', column, '-visible'))
        return int(self.tk.call(self._w, 'column', 'order', column))

    def column_tag_add(self, column, *tags):
        '''Adds each tag in TAGS to the columns specified by the column
        description COLUMN. Duplicate tags are ignored. The list of tags for a
        column can also be changed via column_configure(tags=(...)).'''
        self.tk.call(self._w, 'column', 'tag', 'add', column, tags)

    def column_tag_expr(self, column, tag):
        '''Evaluates the tag expression TAG against every column specified by
        the column description COLUMN. The result is True if the tag expression
        evaluates to True for every column, False otherwise.'''
        return self._getboolean(self.tk.call(
                                self._w, 'column', 'tag', 'expr', column, tag))

    def column_tag_names(self, column):
        '''Returns a list of tag names assigned to the columns specified by the
        column description COLUMN. The result is the union of any tags assigned
        to the columns.'''
        return self.tk.splitlist(self.tk.call(
                                    self._w, 'column', 'tag', 'names', column))

    def column_tag_remove(self, column, *tags):
        '''Removes each tag in TAGS from the columns specified by the column
        description COLUMN. It is not an error if any of the columns do not use
        any of the tags. The list of tags for a column can also be changed via
        column_configure(tags=(...).'''
        self.tk.call(self._w, 'column', 'tag', 'remove', column, tags)

    def column_width(self, column):
        '''This command returns an integer giving the width in pixels of the
        column specified by COLUMN, even if the treectrl is configured to not
        display the column headers by means of the showheader option'''
        return int(self.tk.call(self._w, 'column', 'width', column))

    def contentbox(self):
        '''Returns a tuple with four elements giving the bounding box for the
        space used to display the items, i.e. the space of the treectrl window
        without the surrounding borders or the column headers. The return value
        is None if the content area is totally obscurred by column headers,
        borders, and/or locked columns. Typically this will only happen if the
        window is too small.'''
        return self._getints(self.tk.call(self._w, 'contentbox'))

    def debug_cget(self, element, option):
        '''This command returns the current value of the debugging option named
        OPTION. OPTION may have any of the values accepted by the debug
        configure widget command.'''
        return self.tk.call(self._w, 'debug', 'cget', element, option)

    def debug_configure(self, element, cnf=None, **kw):
        '''This command is similar to the configure widget command except that
        it modifies debugging options instead of modifying options for the
        overall treectrl widget. If no option is specified, the command
        returns a list describing all of the available debugging options.'''
        return self._configure(('debug', 'configure', element), cnf, kw)

    def debug_dinfo(self):
        '''For every of the treectrl widget a line with some internal values
        info about all items is printed to stdout.'''
        self.tk.call(self._w, 'debug', 'dinfo')

    def debug_scroll(self):
        '''Returns a string useful for debugging vertical scrolling.'''
        return self.tk.call(self._w, 'debug', 'scroll')

    def depth(self, itemDesc=None):
        '''If the additional argument ITEMDESC is specified, returns an integer
        giving the depth of the item describing by ITEMDESC, whereas depth is
        defined as the number of steps you must go upward to reach to root
        item. If no ITEMDESC is specified, the maximum depth of all items in
        the treectrl widget is returned instead.'''
        return int(self.tk.call(self._w, 'depth', itemDesc))

    def dragimage_add(self, itemDesc, column=None, element=None):
        '''Adds the shapes of the item described by ITEMDESC to the shapes of
        the dragimage. Specifying additional arguments reduces the number of
        rectangles that are added to the dragimage. If no additional arguments
        is specified, for every element of the item in every column a dotted
        rectangles is added. If COLUMN is specified, all elements in other
        columns are ignored. If also ELEMENT is specified, only a rectangle for
        this one element of the specified item in the given column is added.'''
        return self.tk.call(
                    self._w, 'dragimage', 'add', itemDesc, column, element)

    def dragimage_cget(self, option):
        '''This command returns the current value of the dragimage option named
        OPTION. OPTION may have any of the values accepted by the
        dragimage_configure() widget command.'''
        return self.tk.call(self._w, 'dragimage', 'cget', option)

    def dragimage_clear(self):
        '''Removes all shapes (if there are any) from the dragimage. This
        command does not modify the dragimage offset.'''
        self.tk.call(self._w, 'dragimage', 'clear')

    def dragimage_configure(self, cnf=None, **kw):
        '''This command is similar to the configure widget command except that
        it modifies the dragimage options instead of modifying options for the
        overall treectrl widget. If no option is specified, the command returns
        a list describing all of the available dragimage options '''
        return self._configure(('dragimage', 'configure'), cnf, kw)
    dragimage_config = dragimage_configure

    def dragimage_offset(self, x=None, y=None):
        '''Returns a list containing the x and y offsets of the dragimage, if
        no additional arguments are specified. The dragimage offset is the
        screen distance, the image is displayed relative to the item its shape
        is derived from. If two coordinates are specified, sets the dragimage
        offset to the given coordinates X and Y.'''
        return self._getints(self.tk.call(
                             self._w, 'dragimage', 'offset', x, y))

    def element_cget(self, element, option):
        '''This command returns the current value of the option named OPTION
        associated with the element given by ELEMENT. OPTION may have any of
        the values accepted by the element_configure() widget command.'''
        return self.tk.call(self._w, 'element', 'cget', element, '-'+option)

    def element_configure(self, element, cnf=None, **kw):
        '''This command is similar to the configure() widget command except
        that it modifies options associated with the element given by ELEMENT
        instead of modifying options for the overall treectrl widget. If no
        option is specified, the command returns a list describing all of the
        available options for ELEMENT.'''
        return self._configure(('element', 'configure', element), cnf, kw)
    element_config = element_configure

    def element_create(self, name=None, type=None, *args, **kw):
        '''Create a new elememt in SELF of type TYPE with name NAME. The exact
        format of the arguments after type depends on TYPE, but generally
        consist of specifications for zero or more element options.
        This command returns the name for the new element.'''
        if name is None:
            Treectrl._last_element += 1
            name = 'pyelement' + str(Treectrl._last_element)
        return self._create('element', (name, type, args), kw)
    create_element = element_create

    def element_delete(self, *elements):
        '''Deletes each of the named ELEMENTS. If an element is deleted while
        it is still configured as an element of one or more styles by means of
        the style_elements() widget command, it is also removed from the
        element lists of these styles.'''
        self.tk.call(self._w, 'element', 'delete', *elements)
    delete_element = element_delete

    def element_names(self):
        '''Returns a list containing the names of all existing elements.'''
        return self.tk.splitlist(self.tk.call(self._w, 'element', 'names'))

    def element_perstate(self, element, option, *statelist):
        '''This command returns the value of the per-state option named option
        for element for a certain state. StateList is a list of state names
        (static and dynamic) which specifies the state to use.'''
        return self.tk.call(
                self._w, 'element', 'perstate', element, '-'+option, statelist)

    def element_type(self, element):
        '''Returns the type of the elements given by ELEMENT, such as
        "rect" or "text".'''
        return self.tk.call(self._w, 'element', 'type', element)

    def gradient_cget(self, gradient, option):
        '''Returns the current value of the configuration option for the
        gradient specified by GRADIENT whose name is OPTION. Option may have
        any of the values accepted by the gradient_configure() command.'''
        return self.tk.call(self._w, 'gradient', 'cget', gradient, '-'+option)

    def gradient_configure(self, gradient, cnf=None, **kw):
        '''This command is similar to the configure() widget command except
        that it modifies options associated with the gradient given by GRADIENT
        instead of modifying options for the overall treectrl widget. If no
        option is specified, the command returns a list describing all of the
        available options for GRADIENT.
        The following options are supported (see gradient create for the
        meaning of each option):
            bottom left orient right steps stops top'''
        return self._configure(('gradient', 'configure', gradient), cnf, kw)
    gradient_config = gradient_configure

    def gradient_create(self, name=None, *args, **kw):
        '''Creates a new gradient with the name NAME, which must be a unique
        name not used by another gradient created by this treectrl widget.
        If NAME is None a unique name will be created by the widget.
        The following options are supported:
            -bottom coordSpec
            -left coordSpec
            -right coordSpec
            -top coordSpec
                Each of these options specifies one edge of the gradient brush.
                If the option is specified as an empty string (the default),
                the gradient brush's edge is the same as that of whatever
                rectangle is being painted using the gradient.
                The format of each of these options is a tuple of 2 or more
                values (value, coordType, ?arg ...?), where value is a floating
                point number (usually from 0.0 to 1.0) and coordType is one of
                AREA, CANVAS, COLUMN or ITEM. The AREA keyword must be followed
                by one of the same area names that the bbox command accepts.
                The COLUMN keyword may be followed by a column description
                specifying exactly one column. The ITEM keyword may be followed
                by an item description specifying exactly one item.
            -orient direction
                This option specifies the direction a linear gradient changes
                color in. Must be either horizontal (the default) or vertical
                or an abbreviation of one of these.
            -steps stepCount
                Specifies the number of bands of color drawn for each color
                stop described by the -stops option. The default value is 1,
                the maximum is 25. This option has no effect if gradients are
                drawn using something better than Tk API calls.
            -stops stopsList
                Specifies the color stops along this gradient. The argument
                stopsList has the following form:
                ((offset color ?opacity?), (offset color ?opacity?) ...)
                Each offset is a floating point number from 0.0 to 1.0
                specifying the distance from the start of the gradient
                where the color begins. Each color is a Tk color name or
                description. Each optional opacity is a floating point number
                from 0.0 to 1.0 specifying how transparent the gradient is.
                If stopsList is non-empty there must be at least two stops
                specified, and the first offset must be 0.0 and the last offset
                must be 1.0. Any other stop offsets must be listed in
                increasing order. Specifying opacity has no effect if gradients
                are drawn using Tk API calls.'''
        if name is None:
            Treectrl._last_gradient += 1
            name = 'pygradient' + str(Treectrl._last_gradient)
        return self._create('gradient', (name, args), kw)
    create_gradient = gradient_create

    def gradient_delete(self, *gradients):
        '''Deletes each gradient specified in GRADIENTS. If the gradient is
        still being used then it is not actually deleted until all elements
        etc using the gradient have stopped using it. A deleted-but-in-use
        gradient is not recognized by the various gradient commands.
        Creating a new gradient with the same name as a deleted-but-in-use
        gradient resurrects the deleted gradient.'''
        self.tk.call(self._w, 'gradient', 'delete', *gradients)
    delete_gradient = gradient_delete

    def gradient_names(self):
        '''Returns a list of names of all the gradients that have been
        created by this treectrl widget.'''
        return self.tk.splitlist(self.tk.call(self._w, 'gradient', 'names'))

    def gradient_native(self, preference=None):
        '''Without any arguments, this command returns a boolean indicating
        whether or not the platform supports native transparent gradients.
        The preference argument is a boolean that indicates whether native
        gradients should be used; this can be used to test the appearance
        of the application.'''
        return self._getboolean(self.tk.call(
                                self._w, 'gradient', 'native', preference))

    def identify(self, x, y):
        '''Returns a list containing some diagnostics about what is displayed
        at the given windows coordinates x and y. The resulting list may be
        empty, if nothing is displayed at the given coordinates, otherwise
        the first list element is "header" or "item".
        If the coordinates are in the header area and thus the first element of
        the result is header, the number of the column or the string tail is
        the second element in the resulting list; if the x coordinate is near
        the left or right end of the header, a third element left or right is
        added respectively. If the coordinates are below the header area and
        thus the first element of the result is item, the numerical id of the
        item is the second element in the resulting list. If the x coordinate
        doesn't fall into the column displaying the hierarchical structure,
        the elements column and the column number are added. If the
        x coordinate is within the column displaying the hierarchical
        structure, the following elements are added to the resulting list:
        line and the numerical id of the item the line comes from, if the
        x coordinate is above an item connecting line; button, if the
        x coordinate is above a button; column, the column
        number, elem, and the element name, if the x coordinate is above an
        element of the item; column and the column number, if the x coordinate
        is to the right of the elements; nothing otherwise.'''
        return self.tk.splitlist(self.tk.call(self._w, 'identify', x, y))

    def item_ancestors(self, itemDesc):
        '''Returns a list containing the item ids of the ancestors of the item
        specified by itemDesc. The first list value is the parent, the second
        is the parent's parent, an so on. The last list value will be the root
        item if itemDesc is a descendant of the root item.'''
        return self._getints(self.tk.call(
                                self._w, 'item', 'ancestors', itemDesc))

    def item_bbox(self, itemDesc, column=None, element=None):
        '''Returns a list with four elements giving the bounding box for the
        item described by itemDesc. If no further argument is specified, the
        bbox spans the area of the item over all columns. If a column is
        specified, only the area of the item in this column is considered, if
        an additional element is specified, the area of this element in column
        of the specified item is returned.'''
        return self._getints(self.tk.call(
                self._w, 'item', 'bbox', itemDesc, column, element)) or None

    def item_buttonstate(self, itemDesc, state=None):
        '''If STATE is specified, this command sets the state of the
        expand/collapse button for the single item specified by ITEMDESC.
        The state argument may be one of ACTIVE, NORMAL or PRESSED.
        The current (or newly-set) state of the button is returned.
        The button state is used by the system theme, if any, to change
        the appearance of the button.'''
        return self.tk.call(self._w, 'item', 'buttonstate', itemDesc, state)

    def item_cget(self, itemDesc, option):
        '''Returns the current value of the configuration option for the item
        specified by ITEMDESC whose name is OPTION. OPTION may have any of the
        values accepted by the item_configure() command.'''
        return self.tk.call(self._w, 'item', 'cget', itemDesc, '-'+option)

    def item_children(self, itemDesc):
        '''Returns a list containing the item ids of all children of the item
        specified by ITEMDESC in the correct order from the first child to the
        last child.'''
        return self._getints(self.tk.call(
                            self._w, 'item', 'children', itemDesc)) or ()

    def item_collapse(self, itemDesc, recurse=False, animate=False):
        '''Switches off the open state of the item(s) described by ITEMDESC. If
        the item has descendants, they are no longer displayed. If the item is
        configured to have a button, the button will now display the image or
        bitmap configured with the widget options -buttonimage or
        -buttonbitmap, or a + sign if no image or bitmap is configured.
        If the item is already closed, this command has no effect.
        ITEMDESC may also be the string ALL, in which case all items of the
        treectrl widget are collapsed. If ANIMATE is True, then the item's
        button will animate as it transitions between states if the theme
        supports it; in this case only one item may be specified.
        If RECURSE is True, all descendants of ITEMDESC will also be
        collapsed. For every item, that actually will be collapsed, two events
        are generated: a <Collapse-before> event before the item state is
        changed, and a <Collapse-after> event after the item state was
        changed.'''
        args = (self._w, 'item', 'collapse', itemDesc)
        if recurse:
            args += ('-recurse',)
        if animate:
            args += ('-animate',)
        self.tk.call(*args)

    def item_compare(self, itemDesc1, op, itemDesc2):
        '''From both items described by the ITEMDESCs the index is retrieved
        (as returned from the item_order() widget command). Then these indexes
        are compared using the operator OP, which must be either
        <, <=, ==, >=, >, or != . The return value of this command is True if
        the comparison evaluated to true, False otherwise.'''
        return self._getboolean(self.tk.call(
                        self._w, 'item', 'compare', itemDesc1, op, itemDesc2))

    def item_configure(self, itemDesc, cnf=None, **kw):
        '''If no option is specified, returns a list describing all of the
        available options for the item given by ITEMDESC.
        If option is specified with no value, then the command returns a list
        describing the one named option (this list will be identical to the
        corresponding sublist of the value returned if no option is specified).
        If one or more option-value pairs are specified, then the command
        modifies the given item option(s) to have the given value(s);
        in this case the command returns an empty string.
        The following options are supported by this command (see item_create()
        for the meaning of each option):
        button    boolean
        height    height
        tags      tuple
        visible   boolean
        wrap      boolean'''
        return self._configure(('item', 'configure', itemDesc), cnf, kw)
    item_config = item_configure

    def item_count(self, *args):
        '''If no additional argument is given, returns an integer giving the
        number of items created by the item_create() widget command which
        haven't been deleted by the item_delete() widget command, plus 1 for
        the ever-present root item. If argument(s) are given, the result is the
        number of items that match the item description. For example:
            self.item_count('visible') will return the number of items whose
                                        -visible option is true, and:
            self.item_count('tag', 'a^b') will return the number of items with
                                           either tag "a" or "b", but not both.
        Multiple item descriptions may be combined, like:
            self.item_count('tag', 'foo', 'tag', 'bar', 'visible')'''
        return int(self.tk.call(self._w, 'item', 'count', args or None))

    def item_create(self, *args, **kw):
        '''Creates some new items and optionally returns a list of unique
        identifiers for those items. The new items have the states open and
        enabled set by default. If the treectrl widget currently has the focus,
        the state focus is also set.
        The following options are supported by this command:
        -button boolean
            Boolean indicates whether or not an expand/collapse button should
            be drawn next to this item, typically to indicate the item has
            children. The button will only be displayed if: a) the column
            specified by the treectrl option -treecolumn is visible;
            and b) the treectrl option -showbuttons is true
        -count numItems
            Specifies the number of items to create. Must be >= 0.
            Defaults to 1.
        -enabled boolean
            Specifies whether the items should be enabled. Default is true.
        -height height
            Specifies a fixed height in any of the forms acceptable to
            Tk_GetPixels. Must be >= 0. If height is zero then the item's
            height is unspecified. Defaults to 0.
        -nextsibling itemDesc
            Specifies the item before which the new items will be inserted.
            The new items will have the same parent as itemDesc.
        -open boolean
            Specifies whether the items should be open or closed.
            Default is true.
        -parent itemDesc
            Specifies the item which the new items will be the children of.
            The new items will be appended to the list of children of itemDesc.
        -prevsibling itemDesc
            Specifies the item after which the new items will be inserted. The
            new items will have the same parent as itemDesc.
        -returnid boolean
            Specifies whether or not to return a list of item identifiers for
            the newly created items. Specifying false is useful when creating
            a large number of items in the console or to improve performance.
            Default is true.
        -tags tuple
            Tags are textual labels applied to items to group them. Tags do
            not affect the appearance or behaviour of items. Tags can be used
            in item descriptions to operate on multiple items.
        -visible boolean
            It indicates that the item should be displayed
            in the list. The item will only be displayed if: a) each ancestor
            is a descendant of the root item (not an orphan); and
            b) each ancestor's -visible option is true.
        -wrap boolean
            When this option is true an item will be the first in a horizontal
            (when the treectrl option -orient=horizontal) or a vertical (when
            the treectrl option -orient=vertical) range of items.
        '''
        return self._getints(self._create('item', args, kw)) or None
    create_item = item_create

    def item_delete(self, first, last=None):
        '''Deletes the specified item(s). FIRST and LAST must be the string
        ALL or a valid item description. If either FIRST or LAST is specified
        as ALL, then all items are deleted. If FIRST is specified and LAST
        isn't specified, the item described by FIRST is deleted. If both FIRST
        and LAST are specified, they must decribe items with a common ancestor;
        then the range of items between FIRST and LAST is deleted. Deleting an
        item deletes any child items of the deleted item recursively. If the
        current active item is deleted, the root item becomes the new active
        item. If the current selection anchor item is deleted, the root item
        becomes the new anchor item. There is no way to delete the root item
        of the treectrl widget; in all cases the specification of the root item
        is ignored. For each call to this command, two events may be generated.
        If any of the deleted items are selected, then a <Selection> event is
        generated just before the items are deleted. If any items were actually
        deleted, then an <ItemDelete> event is generated just before the items
        are deleted.'''
        self.tk.call(self._w, 'item', 'delete', first, last)
    delete_item = item_delete

    def item_descendants(self, itemDesc):
        '''Returns a tuple containing the item ids of the descendants of the
        item specified by itemDesc, i.e. the children, grandchildren,
        great-grandchildren etc, of the item.'''
        return self._getints(self.tk.call(
                                self._w, 'item', 'descendants', itemDesc))

    def item_dump(self, itemDesc):
        '''Returns a list with four elements in the form
        (index, *index*, indexVis, *indexVis*).'''
        return self.tk.splitlist(self.tk.call(
                                    self._w, 'item', 'dump', itemDesc))

    def itemelement_cget(self, itemDesc, column, element, option):
        '''This command returns the value of the option named OPTION associated
        with ELEMENT inside COLUMN of the item described by ITEMDESC, if it
        was already configured for the actual item. OPTION may have any of the
        values accepted by the type of the specified ELEMENT.'''
        return self.tk.call(self._w, 'item', 'element', 'cget', itemDesc,
                            column, element, '-'+option)

    def itemelement_configure(self, itemDesc, column, element, cnf=None, **kw):
        '''This command is similar to the configure widget command except that
        it modifies options associated with ELEMENT inside COLUMN of the item
        described by ITEMDESC instead of modifying options for the overall
        treectrl widget. If no option is specified, the command returns a list
        describing all of the available options for the element'''
        return self._configure(('item', 'element', 'configure',
                                itemDesc, column, element), cnf, kw)
    itemelement_config = itemelement_configure

    def itemelement_perstate(self, itemDesc, column, element,
                             option, *statelist):
        '''This command returns the current value of the per-state option named
        OPTION for ELEMENT inside COLUMN of the item described by ITEMDESC.
        If STATELIST is specified, the list of state names (static and dynamic)
        is used in place of the current state for ITEM and COLUMN.'''
        return self.tk.call(self._w, 'item', 'element', 'perstate', itemDesc,
                            column, element, '-'+option, statelist)

    def item_enabled(self, itemDesc, enabled=None):
        '''Returns True if the item described by ITEMDESC has the state
        "enabled" switched on, False otherwise. If ENABLED is specified, then
        the "enabled" state of every item described by the item description
        ITEMDESC is set accordingly. All items are enabled when first created.
        Disabled items cannot be selected, and are ignored by the default
        key-navigation and mouse bindings.'''
        return self._getboolean(self.tk.call(
                                self._w, 'item', 'enabled', itemDesc, enabled))

    def item_expand(self, itemDesc, recurse=False, animate=False):
        '''Switches on the open state of the item(s) described by ITEMDESC. If
        the item has descendants, they are now displayed. If the item is
        configured to have a button, the button will now display the image or
        bitmap configured with the widget options -buttonimage or
        -buttonbitmap, or a - sign if no image or bitmap is configured.
        If the item is already open, this command has no effect.
        If ANIMATE is specified, then the item's button will animate as it
        transitions between states if the theme supports it; in this case only
        one item may be specified. ItemDesc may also be the string ALL, in
        which case all items of the treectrl widget are expanded.
        If RECURSE is True, all descendants of ITEMDESC will
        also be expanded. For every item, that actually will be expanded,
        two events are generated: an <Expand-before> event before the
        item state is changed, and an <Expand-after> event after the
        item state was changed.'''
        args = (self._w, 'item', 'expand', itemDesc)
        if recurse:
            args += ('-recurse',)
        if animate:
            args += ('-animate',)
        self.tk.call(*args)

    def item_firstchild(self, parent, child=None):
        '''If CHILD is not specified, returns the item id of the first child of
        the item described by PARENT. If CHILD is specified, it must describe
        an item that is not an ancestor of PARENT. Then it will become the new
        first child of PARENT.'''
        res = self.tk.call(self._w, 'item', 'firstchild', parent, child)
        if res == '':
            return None
        return int(res)

    def item_id(self, itemDesc):
        '''New in treectrl-2.2 :
        This command resolves the item description ITEMDESC into a
        tuple of unique item identifier(s).If ITEMDESC doesn't refer to any
        existing items, then this command returns None. For example:
            self.item_id(ALL) will return a tuple of ids for all items, and:
            self.item_id(self.item_children(someItem)) will return the ids of
                                                       every child of an item.
        On previous versions of the treectrl widget, a tuple containing only
        one item id will be returned.'''
        return self._getints(self.tk.call(self._w, 'item', 'id', itemDesc))

    def item_image(self, itemDesc, *columnAndImage):
        '''This command sets or retrieves the value of the per-state -image
        option for the first image element in one or more columns. If no column
        is specified, this command returns a list of values, one per column. If
        no image is specified, this command returns the value for column. If
        one or more column-image pairs is specified, then the value of the
        -image option in each column is set to image. Note that this command is
        provided as a convenience. Use the itemelement_configure() or
        itemelement_cget() commands if you want to set or retrieve the value
        of the -image option for a specific image element.'''
        return self.tk.splitlist(self.tk.call(
                self._w, 'item', 'image', itemDesc, *columnAndImage)) or None

    def item_isancestor(self, itemDesc, descendant):
        '''Returns True if the item described by ITEMDESC is a direct or
        indirect parent of the item decribed by DESCENDANT, False otherwise.'''
        return self._getboolean(self.tk.call(
                        self._w, 'item', 'isancestor', itemDesc, descendant))

    def item_isopen(self, itemDesc):
        '''Returns True if the item described by itemDesc has the state open
        switched on, False otherwise.'''
        return self._getboolean(self.tk.call(
                                    self._w, 'item', 'isopen', itemDesc))

    def item_lastchild(self, parent, child=None):
        '''If CHILD is not specified, returns the item id of the last child of
        the item described by PARENT. If CHILD is specified, it must describe
        an item that is not an ancestor of PARENT. Then it will become the new
        last child of PARENT.'''
        res = int(self.tk.call(self._w, 'item', 'lastchild', parent, child))
        if res == '':
            return None
        return int(res)

    def item_nextsibling(self, sibling, next=None):
        '''If NEXT is not specified, returns the item id of the next sibling of
        the item described by SIBLING. If NEXT is specified, it must describe
        an item that is not an ancestor of SIBLING. Then it will become the new
        next sibling of SIBLING.'''
        res = self.tk.call(self._w, 'item', 'nextsibling', sibling, next)
        if res == '':
            return None
        return int(res)

    def item_numchildren(self, itemDesc):
        '''Returns the number of children of the item described by ITEMDESC.'''
        return int(self.tk.call(self._w, 'item', 'numchildren', itemDesc))

    def item_order(self, itemDesc, visible=False):
        '''This command returns the position of the item ITEMDESC relative to
        its toplevel ancestor (usually the root item, unless the ancestor is an
        orphan). If you imagine all the items flattened into a vertical list,
        the result of this command is the row the item falls in. If the
        optional argument -visible is given, only the items whose ancestors
        are expanded, and whose -visible option is true, get counted; in this
        case -1 is returned if the item is not visible.'''
        if visible:
            return int(self.tk.call(
                            self._w, 'item', 'order', itemDesc, '-visible'))
        return int(self.tk.call(self._w, 'item', 'order', itemDesc))

    def item_parent(self, itemDesc):
        '''Returns the item id of the parent of the item described by
        ITEMDESC.'''
        return int(self.tk.call(self._w, 'item', 'parent', itemDesc))

    def item_prevsibling(self, sibling, prev=None):
        '''If PREV is not specified, returns the item id of the previous
        sibling of the item described by SIBLING. If PREV is specified, it
        must describe an item that is not an ancestor of SIBLING. Then it will
        become the new previous sibling of SIBLING.'''
        res = self.tk.call(self._w, 'item', 'prevsibling', sibling, prev)
        if res == '':
            return None
        return int(res)

    def item_range(self, first, last):
        '''Returns a list containing the item ids of all items in the range
        between FIRST and LAST, inclusive. The order between FIRST and LAST
        doesn't matter, and the result is always sorted by the increasing order
        of the items (as returned by the item order command). The items
        specified by FIRST and LAST must share a common ancestor.'''
        return self._getints(self.tk.call(
                                self._w, 'item', 'range', first, last))

    def item_remove(self, itemDesc):
        '''Removes the item described by ITEMDESC from the list of children of
        its parent, so that it will become an orphan.'''
        self.tk.call(self._w, 'item', 'remove', itemDesc)

    def item_rnc(self, itemDesc):
        '''Returns a list of two integers, which corresponds to the row and
        column of the item described by ITEMDESC. The row and column
        corresponds to the on-screen arrangement of items as determined by
        the -orient and -wrap options.
        If the item is not displayed, this command returns None.'''
        return self._getints(self.tk.call(
                                self._w, 'item', 'rnc', itemDesc)) or None

    def item_sort(self, itemDesc, column=None, element=None, first=None,
                  last=None, mode=None, command=None, notreally=False):
        '''Sorts the children of the item described by ITEMDESC, and redisplays
        the tree with the items in the new order. The range of items which
        should be sorted can be restricted by means of the FIRST and/or LAST
        options, which should be children of the item described by ITEMDESC;
        the order between these two limiting items doesn't matter. The sort
        column can be specified by means of the COLUMN option; this option
        can be used repeatedly to define a multicolumn sort. The sorting is
        done by looking at the text of the element specified by the ELEMENT
        option, which must be a text element defined in the style of the
        sorting column; by default the first text element is used.
        If the NOTREALLY option is True, no rearranging of the items is
        done; instead the sorted items are returned as result of the command.
        By default ASCII sorting is used with the result returned in increasing
        order. Any of the following options (or a sequence of options) may be
        specified as MODE to control the sorting process of the previously
        specified column (unique abbreviations are accepted):
        ascii
            Use string comparison with ASCII collation order.
            This is the default.
        command command
            Use command as a comparison command. To compare two items,
            evaluate a command with the numerical ids of the two items passed
            as arguments. The comamnd should return an integer less than,
            equal to, or greater than zero if the first item is to be
            considered less than, equal to, or greater than the second,
            respectively.
        decreasing
            Sort the items in decreasing order ("largest" items first).
        dictionary
            Use dictionary-style comparison. This is the same as -ascii except
            (a) case is ignored except as a tie-breaker and
            (b) if two strings contain embedded numbers, the numbers compare
            as integers, not characters. For example, in -dictionary mode,
            bigBoy sorts between bigbang and bigboy,
            and x10y sorts between x9y and x11y.
        increasing
            Sort the items in increasing order ("smallest" items first).
            This is the default.
        integer
            Convert to integers and use integer comparison.
        real
            Convert to floating-point values and use floating comparison.'''
        # FIXME: looks ugly, but at least it seems to work now...
        # the problem is that the order of the args seems to matter here
        args = (self._w, 'item', 'sort', itemDesc)
        if column != None:
            args = args + ('-column', column)
        if element != None:
            args = args + ('-element', element)
        if first != None:
            args = args + ('-first', first)
        if last != None:
            args = args + ('-last', last)
        if command != None:
            cmd = self._register(command)
            args = args + ('-command', cmd)
        if mode:
            # mode may be a string or a sequence of strings
            if isinstance(mode, str):
                args = args + ('-' + mode,)
            else:
                args = args + tuple(['-' + m for m in mode])
        if notreally:
            notreally = '-notreally'
        else:
            notreally = None
        args = args + (notreally,)
        return self.tk.splitlist(self.tk.call(*args)) or None

    def item_span(self, itemDesc, *columnAndNumColumns):
        '''This command sets or retrieves the number of columns that a style
        covers. If no column is specified, the return value is a list of spans,
        one per column. If no numColumns is specified, the return value is the
        span for column. If one or more column-numColumns pairs is specified,
        the span for each column is set to numColumns.'''
        if not columnAndNumColumns:
            return self._getints(self.tk.call(
                                    self._w, 'item', 'span', itemDesc))
        if not columnAndNumColumns[1:]:
            return int(self.tk.call(
                    self._w, 'item', 'span', itemDesc, *columnAndNumColumns))
        self.tk.call(self._w, 'item', 'span', itemDesc, *columnAndNumColumns)

    def itemstate_forcolumn(self, itemDesc, column, *statenames):
        '''Just like itemstate_set() but manipulates dynamic states for a
        single item column, not the item as a whole. If STATENAME is
        unspecified, this command returns a list containing the names of all
        the dynamic states which are switched on in COLUMN.'''
        return self.tk.splitlist(self.tk.call(self._w, 'item', 'state',
                    'forcolumn', itemDesc, column, statenames or None)) or None

    def itemstate_get(self, itemDesc, statename=None):
        '''If no STATENAME is specified, returns a list containing the names of
        all (static and dynamic) states which are currently switched on for the
        item described by ITEMDESC. If a STATENAME is specified, True is
        returned if the specified state is currently switched on for the item,
        False otherwise.'''
        if statename:
            return self._getboolean(self.tk.call(
                        self._w, 'item', 'state', 'get', itemDesc, statename))
        return self.tk.splitlist(self.tk.call(
                        self._w, 'item', 'state', 'get', itemDesc))

    def itemstate_set(self, first, last, *statenames):
        '''Every element of STATENAMES must be the name of a dynamic state,
        optionally preceded by a ~ or ! character. Every state with a
        leading ! will be switched off for the item described by FIRST, every
        state with a leading ~ will be toggled, and every state without
        leading ! or ~ will be switched on. If LAST is specified, the state
        changes will be made for all items in the range between FIRST and LAST.
        If LAST is set to None, only the state(s) of the item described by
        FIRST will be changed. If FIRST is the string ALL, then the state
        changes are made for all items of the treectrl widget.'''
        # Too bad, this was poorly designed in the first version and now we
        # cannot fix it without making it backwards incompatible;
        # say we have two states "foo" and "bar", the following works:
        #    tree.itemstate_set(2, '~bar')          but
        #    tree.itemstate_set(2, '~foo', '~bar')   gives an error:
        #           _tkinter.TclError: item "~foo" doesn't exist
        #  so instead we need to do:
        #    tree.itemstate_set(2, None,'~foo', '~bar')
        #  which seems somewhat clumsy;
        #       tree.itemstate_set(2, 4, '~foo', '~bar')
        #   at least works as expected.
        #  Another odd thing is that if we pass an empty tuple as "statenames"
        #  it will be silently ignored by Tk, however if we pass None, we get:
        #  _tkinter.TclError: wrong # args: should be
        #  ".4128887724.4128887980 item state set item ?last? stateList" ,
        #  as one would expect.
        #  The same happens of course in tcl with:
        #  % .t item state set 0 {} -> ok  vs. % .t item state set 0 "" -> err.
        # As this behavior is not documented it is probably better to be strict
        # about this and not allow empty statenames tuples
        # To make this all a little less awkward than the first version,
        # we can differ between three ways to invoke this function:

        # 1.  tree.itemstate_set(2, None,'~foo', '~bar')     -> the proper way
        if last is None:
            self.tk.call(self._w, 'item', 'state', 'set',
                                    first, statenames or None)
        # 2.  tree.itemstate_set(2, 4, '~foo', '~bar')     -> the proper way
        # beware: tree.itemstate_set(2, '~foo', '~bar') will raise a TclError !
        elif statenames:
            self.tk.call(self._w, 'item', 'state', 'set',
                                    first, last, statenames)
        # 3.  tree.itemstate_set(2, '~bar')  -> bad, but we better keep this
        #                         legal, otherwise we would break existing code
        else:
            # now "last" actually serves as our statenames tuple
            self.tk.call(self._w, 'item', 'state', 'set', first, (last,))

    def itemstyle_elements(self, itemDesc, column):
        '''This command returns a list containing the names of elements which
        were configured by the itemelement_configure() command for the item
        described by ITEMDESC in COLUMN.
        If there is no style assigned to COLUMN, None is returned.'''
        try:
            return self.tk.splitlist(self.tk.call(
                    self._w, 'item', 'style', 'elements', itemDesc, column))
        except tkinter.TclError:
            return None

    def itemstyle_map(self, itemDesc, column, style, *map):
        '''Like the itemstyle_set() command, this command may be used to assign
        a style to a specific column of an item. Unlike itemstyle_set(), this
        command can transfer configuration values of elements in the current
        style to elements in the new style specified by STYLE. MAP must be a
        list of elementOld-elementNew pairs, where elementOld is an element in
        the current style, and elementNew is an element in the style specified
        by style. Both elementOld and elementNew must be of the same
        type (bitmap, text etc).'''
        self.tk.call(self._w, 'item', 'style', 'map',
                                        itemDesc, column, style, map)

    def itemstyle_set(self, itemDesc, *columnAndStyle):
        '''This command sets or retrieves the style assigned to one or more
        columns. If no COLUMN is specified, this command returns a tuple
        containing the names of the styles set for all columns of the item
        described by ITEMDESC. If no STYLE is specified, this command returns
        the name of the style set for the item described by ITEMDESC in COLUMN.
        If one or more column-style pairs is specified, then the style in each
        column is set to style.'''
        return self.tk.splitlist(self.tk.call(self._w, 'item', 'style', 'set',
                                        itemDesc, *columnAndStyle)) or None

    def item_tag_add(self, itemDesc, *tags):
        '''Adds each tag in TAGS to the items specified by the item description
        ITEMDESC. Duplicate tags are ignored. The list of tags for an item can
        also be changed via item_configure(tags=(...)).'''
        self.tk.call(self._w, 'item', 'tag', 'add', itemDesc, tags)

    def item_tag_expr(self, itemDesc, tag):
        '''Evaluates the tag expression TAG against every column specified by
        the item description ITEMDESC. The result is True if the tag expression
        evaluates to true for every item, False otherwise. For example:
            self.item_tag_expr(itemDesc, 'foo')
        returns True if an item has tag "foo". Also:
            self.item_tag_expr(itemDesc, 'a||b')
        returns True if  an item has tag "a" or "b".'''
        return self._getboolean(self.tk.call(
                            self._w, 'item', 'tag', 'expr', itemDesc, tag))

    def item_tag_names(self, itemDesc):
        '''Returns a list of tag names assigned to the items specified by the
        item description ITEMDESC. The result is the union of any tags assigned
        to the items.'''
        return self.tk.splitlist(self.tk.call(
                            self._w, 'item', 'tag', 'names', itemDesc))

    def item_tag_remove(self, itemDesc, *tags):
        '''Removes each tag in TAGS from the items specified by the item
        description ITEMDESC. It is not an error if any of the items do not use
        any of the tags. The list of tags for an item can also be changed via
        item_configure(tags=(...).'''
        self.tk.call(self._w, 'item', 'tag', 'remove', itemDesc, tags)

    def item_text(self, itemDesc, *columnAndText):
        '''This command sets or retrieves the value of the -text option for the
        first text element in one or more columns. If no COLUMN is specified,
        this command returns a list of values, one per column. If no TEXT is
        specified, this command returns the value for COLUMN. If one or more
        column-text pairs is specified, then the value of the -text option in
        each column is set to text. Note that this command is provided as a
        convenience. Use the itemelement_configure() or itemelement_cget()
        commands if you want to set or retrieve the value of the -text option
        for a specific text element.'''
        return self.tk.splitlist(self.tk.call(self._w, 'item', 'text',
                                        itemDesc, *columnAndText)) or None

    def item_toggle(self, itemDesc, recurse=False, animate=False):
        '''Changes the open state of the item(s) described by ITEMDESC. If the
        state is currently switched off, this command does the same as the
        item_expand() widget command, otherwise the same as the item_collapse()
        widget command. If ANIMATE is specified, then the item's button will
        animate as it transitions between states if the theme supports it; in
        this case only one item may be specified.ITEMDESC may also be the
        string ALL, in which case the state of all items of the treectrl widget
        are toggled. If RECURSE is specified, the state of all descendants of
        ITEMDESC will also be toggled.'''
        args = (self._w, 'item', 'toggle', itemDesc)
        if recurse:
            args += ('-recurse',)
        if animate:
            args += ('-animate',)
        self.tk.call(*args)

    def marquee_anchor(self, x=None, y=None):
        '''Returns a list containing the x and y coordinates of the anchor, if
        no additional arguments are specified. If two coordinates are
        specified, sets the anchor to the given coordinates X and Y.'''
        return self._getints(self.tk.call(
                             self._w, 'marquee', 'anchor', x, y)) or None

    def marquee_cget(self, option):
        '''This command returns the current value of the marquee option named
        OPTION. OPTION may have any of the values accepted by the
        marquee_configure() widget command.'''
        return self.tk.call(self._w, 'marquee', 'cget', '-'+option)

    def marquee_configure(self, cnf=None, **kw):
        '''This command is similar to the configure() widget command except
        that it modifies the marquee options instead of modifying options for
        the overall treectrl widget.
        The following marquee options are supported:
        -fill
          Specifies the fill color for the selection rectangle. The value can
          be a Tk color or a gradient name or an empty string (the default).
          When this option isn't an empty string the dotted outline is not
          drawn. By specifying the name of a semi-transparent gradient a
          modern-looking selection rectangle can be achieved.
        -outline
          Specifies the outline color for the selection rectangle. The value
          can be a Tk color, a gradient name, or an empty string which is the
          default.  When this option isn't an empty string the dotted outline
          is not drawn.
        -visible boolean
          Specifies a boolean value which determines whether the dotted line
          surrounding the region of the marquee should currently be visible.'''
        return self._configure(('marquee', 'configure'), cnf, kw)

    def marquee_coords(self, x1=None, y1=None, x2=None, y2=None):
        '''Returns a list containing the x and y coordinates of the anchor
        followed by the x and y coordinates of the corner, if no additional
        arguments are specified. If four coordinates are specified, sets the
        anchor to the given coordinates x1 and y1 and the corner to the
        coordinates x2 and y2. '''
        return self._getints(self.tk.call(self._w, 'marquee', 'coords',
                                          x1, y1, x2, y2)) or None

    def marquee_corner(self, x=None, y=None):
        '''Returns a list containing the x and y coordinates of the corner,
        if no additional arguments are specified. If two coordinates are
        specified, sets the corner to the given coordinates x and y.'''
        return self._getints(self.tk.call(
                                self._w, 'marquee', 'corner', x, y)) or None

    def marquee_identify(self):
        '''Returns a list with information about the items inside the marquee.
        The list has as elements a list itself for every item which is
        displayed inside the marquee. The first element of these lists is the
        numerical item id, followed by another list with information about
        every column of the item inside the marque. These lists start with the
        column number, followed by the elements of the style defined for the
        item in this column if there are any.'''
        return self.tk.splitlist(self.tk.call(self._w, 'marquee', 'identify'))

    def notify_bind(self, sequence=None, func=None, object=None, add=None):
        '''This command associates Tcl scripts with events generated by a
        treectrl widget. If all three arguments are specified, notify_bind()
        will arrange for FUNC to be evaluated whenever the event(s) specified
        by SEQUENCE are generated by this treectrl widget. If ADD is True,
        then it is appended to any existing binding for SEQUENCE; otherwise
        FUNC replaces any existing binding. If FUNC is an empty string, then
        the current binding for SEQUENCE is destroyed, leaving SEQUENCE
        unbound. If SEQUENCE is specified without a FUNC, then the script
        currently bound to SEQUENCE is returned, or an empty string is returned
        if there is no binding for SEQUENCE. If neither SEQUENCE nor FUNC is
        specified, then the return value is a list whose elements are all the
        patterns for which there exist bindings for object. The OBJECT argument
        determines which window(s) the binding applies to. If OBJECT begins
        with a dot, as in .a.b.c, then it must be the path name for a window;
        otherwise it may be an arbitrary string. Like the regular bind command,
        bindings on window names are automatically removed if that window is
        destroyed.'''
        # mainly stolen from tkinter.Misc._bind()
        if object in (None, self):
            object = self._w
        if isinstance(func, str):
            self.tk.call(self._w, 'notify','bind', object, sequence, func)
        elif func:
            funcid = self._register(func, self._substitute_notify, 1)
            cmd = ('%sif {"[%s %s]" == "break"} break\n' % (
                    add and '+' or '', funcid, self._subst_format_str_notify))
            self.tk.call(self._w, 'notify','bind', object, sequence, cmd)
            return funcid
        elif sequence:
            return self.tk.call(self._w, 'notify','bind',
                                    object, sequence) or None
        else:
            return self.tk.splitlist(self.tk.call(
                                        self._w, 'notify','bind', object))

    def notify_configure(self, object, sequence, cnf=None, **kw):
        '''This command sets and retrieves options for bindings created by the
        notify_bind() command. If no option is specified, the command returns
        a list with option-value pairs describing all the available binding
        options for SEQUENCE on OBJECT. If option is specified with no value,
        then the command returns the current value of that option. If one or
        more option-value pairs are specified, then the command modifies the
        given option(s) to have the given value(s) for the binding; in this
        case the command returns an empty string.
        The following binding options are supported:
        -active boolean
            Specifies if the binding should be active. As long as this option
            is specified as false, a binding script will not be evaluated
            when the corresponding event is generated.'''
        return self._configure(('notify', 'configure',
                                    object, sequence), cnf, kw)
    notify_config = notify_configure

    def notify_detailnames(self, eventname):
        '''Returns a list containing the names of all details, which are
        installed for the event with the name EVENTNAME by means of the
        notify_install() widget command or by the treectrl widget itself.'''
        return self.tk.splitlist(self.tk.call(
                                 self._w, 'notify', 'detailnames', eventname))

    def notify_eventnames(self):
        '''Returns a list containing the names of all events, which are
        installed by means of the notify_install() widget command or by the
        treectrl widget itself.'''
        return self.tk.splitlist(self.tk.call(self._w, 'notify', 'eventnames'))

    def notify_generate(self, sequence, charmap=None,
                        percentscommand=None, **kw):
        '''This command causes the treectrl widget to generate an event. This
        command is typically used to generate dynamic events created by the
        notify_install() command, but may be used to generate static events
        also. The event specified by SEQUENCE is generated, and any active
        binding scripts on the event are evaluated after undergoing
        %-substitution. If there are details defined for the event, SEQUENCE
        must describe an <eventName-detail> pair, otherwise SEQUENCE should
        be <eventName>. The optional CHARMAP is a tuple of char-value pairs.
        Each char has to be exactly one character. The charMap is used in
        %-substitution. If PERCENTSCOMMAND is specified, then it will be used
        to perform %-substitution on any scripts bound to the event. If
        PERCENTSCOMMAND is not specified and the event is dynamic, then the
        %-subtitution command passed to notify_install() will be used if it was
        provided. If the event is static or no %-substitution command is
        available, then all %-substitution is done using CHARMAP only . See
        notify_install() for a description of PERCENTSCOMMAND. If no CHARMAP is
        specified, a default charmap will be created, that contains information
        about the widget and the event pattern, plus optional information
        provided by keyword-value pairs; any of the attributes of a
        TreectrlEvent instance as created by a notify_bind() callback is
        accepted as keyword argument.'''
        if charmap is None:
            charmap = ['b', None, 'c', None, 'd', None, 'e', None, 'i', None,
                       'h', None, 'l', None, 'p', None, 't', None, 'u', None,
                       'v', None, 'C', None, 'D', None, 'E', None, 'I', None,
                       'P', sequence, 'S', None, 'W', self._w, 'T', self._w]
            if 'columnbefore' in kw: charmap[1] = kw['columnbefore']
            if 'active' in kw or 'selectcount' in kw:
                try:
                    charmap[3] = kw['active']
                except KeyError:
                    charmap[3] = kw['selectcount']
            # get name and detail
            s = sequence.strip('<').strip('>')
            try:
                charmap[5] = s.split('-')[1]
            except IndexError:
                pass
            charmap[7] = s.split('-')[0]
            if 'deleteditems' in kw: charmap[9] = kw['deleteditems']
            if 'nonvisible' in kw: charmap[11] = kw['nonvisible']
            if 'lower' in kw or 'draggeditems' in kw:
                try:
                    charmap[13] = kw['lower']
                except KeyError:
                    charmap[13] = kw['draggeditems']
            if 'prevactive' in kw: charmap[15] = kw['prevactive']
            if 'text' in kw: charmap[17] = kw['text']
            if 'upper' in kw: charmap[19] = kw['upper']
            if 'visible' in kw: charmap[21] = kw['visible']
            if 'column' in kw: charmap[23] = kw['column']
            if 'deselected' in kw: charmap[25] = kw['deselected']
            if 'textelement' in kw: charmap[27] = kw['textelement']
            if 'item' in kw: charmap[29] = kw['item']
            if 'selected' in kw: charmap[33] = kw['selected']
            if 'object' in kw: charmap[35] = kw['object']
            charmap = tuple(charmap)
        self.tk.call(self._w, 'notify', 'generate',
                     sequence, charmap, percentscommand)

    def notify_install(self, sequence, percentscommand=None):
        '''This command installs a new event or detail specified by SEQUENCE.
        Events created by this command are called dynamic, whereas events
        created by the treectrl widget itself are called static. This command
        may be called to set or retrieve the PERCENTSCOMMAND for an existing
        dynamic event. The optional PERCENTSCOMMAND is a list containing the
        name of a Tcl command, plus any optional arguments, to which five
        additional arguments will be appended. The command will be called to
        perform %-substitution on any scripts bound to the event specified by
        SEQUENCE. notify_install() returns the current PERCENTSCOMMAND for the
        event, or an error if the event is not dynamic.'''
        # FIXME: percentscmd
        return self.tk.call(self._w, 'notify', 'install',
                            sequence, percentscommand) or None
        #raise 'Function not yet implemented: "notify_install()"'

    def notify_linkage(self, sequence):
        '''Returns a string indicating whether the specified event or detail
        is created by means of the notify_install() widget command (dynamic)
        or by the treectrl widget itself (static).'''
        return self.tk.call(self._w, 'notify', 'linkage', sequence)

    def notify_unbind(self, object, sequence=None):
        '''If no SEQUENCE is specified, all bindings on OBJECT are removed.
        If SEQUENCE is specified, then the current binding for SEQUENCE is
        destroyed, leaving SEQUENCE unbound.'''
        self.tk.call(self._w, 'notify', 'unbind', object, sequence)

    def notify_uninstall(self, sequence):
        '''If the event or detail specified by SEQUENCE is static (i.e. created
        by the treectrl widget itself), an error is generated. Otherwise the
        dynamic event or detail is removed. If an event name is specified
        without a detail, all details for that event are also removed.'''
        self.tk.call(self._w, 'notify', 'uninstall', sequence)

    def orphans(self):
        '''Returns a list containing the item ids of all items which have no
        parent. When an item is created, it has no parent by default, and can
        later become an orphan by means of the item_remove() widget command.
        The root item is not returned.'''
        return self._getints(self.tk.call(self._w, 'orphans'))

    def state_define(self, statename):
        '''Defines a new state with the name STATENAME, which must not be the
        name of an existing state.'''
        self.tk.call(self._w, 'state', 'define', statename)

    def state_linkage(self, statename):
        '''Returns a string indicating whether the specified state is
        user-defined by means of the state_define() widget command (dynamic)
        or predefined by the treectrl widget itself (static).'''
        return self.tk.call(self._w, 'state', 'linkage', statename)

    def state_names(self):
        '''Returns a list containing the names of all user-defined states.'''
        return self.tk.splitlist(self.tk.call(self._w, 'state', 'names'))

    def state_undefine(self, statename):
        '''STATENAME must be the name of a user-defined state. Removes this
        state from the list of user-defined states.'''
        self.tk.call(self._w, 'state', 'undefine', statename)

    def see(self, itemDesc, column=None, center=None):
        '''Adjust the view in the treectrl so that the item described by
        ITEMDESC is visible. If the item is already visible then the command
        has no effect; otherwise the treectrl scrolls to bring the item into
        view, and the corresponding <Scroll-x> and/or <Scroll-y> events are
        generated. If COLUMN is specified then a specific column of the item
        is scrolled into view instead of the entire item.
        CENTER may be a string that contains zero or more of the characters
        "x" or "y". This option is used to center the item horizontally and/or
        vertically in the window. The item will be centered regardless of
        whether it is already visible.'''
        args = (itemDesc, column)
        if not center is None:
            args += ('-center', center)
        self.tk.call(self._w, 'see', *args)

    def selection_add(self, first, last=None):
        '''FIRST and LAST (if specified) must be the string ALL or a valid
        item description. Adds every unselected item in the range between
        FIRST and LAST, inclusive, to the selection without affecting the
        selection state of items outside that range. If one of the arguments
        is the string ALL, every unselected item in the treectrl widget is
        added to the selection. A <Selection> event is generated if any
        items were added to the selection.'''
        self.tk.call(self._w, 'selection', 'add', first, last)

    def selection_anchor(self, itemDesc=None):
        '''If ITEMDESC is specified, the selection anchor is set to the
        described item. The selection anchor is the end of the selection that
        is fixed while dragging out a selection with the mouse. The item
        description anchor may be used to refer to the anchor item. This
        command doesn't modify the selection state of any item. Returns the
        numerical id of the selection anchor item.'''
        return int(self.tk.call(self._w, 'selection', 'anchor',
                                itemDesc)) or None

    def selection_clear(self, first=None, last=None):
        '''FIRST and LAST (if specified) must be the string ALL or a valid
        item description. If any of the items between FIRST and LAST
        (inclusive) are selected, they are deselected. The selection state is
        not changed for items outside this range. If no additional arguments
        are given, or if one of the arguments is the string ALL, then all
        items are removed from the selection. A <Selection> event is
        generated if any items were removed from the selection.'''
        self.tk.call(self._w, 'selection', 'clear', first, last)

    def selection_count(self):
        '''Returns an integer indicating the number of items in the treectrl
        that are currently selected.'''
        return int(self.tk.call(self._w, 'selection', 'count'))

    def selection_get(self, first=None, last=None):
        '''Returns a tuple containing the item ids of all of the items in the
        treectrl that are currently selected. If there are no items selected
        in the treectrl, returns None. The optional arguments FIRST and LAST
        are treated as indices into the sorted list of selected items.
        For example:
            self.selection_get(0)          : the first selected item
            self.selection_get("end")      : the last selected item
            self.selection_get(1, "end-1") : every selected item except
                                             the first and last'''
        # at least with treectrl-2.2.9
        # self.tk.call(self._w, 'selection', 'get', 0, "end") returns an
        # integer instead of a tuple when a single item is selected,
        # so we cannot simply use:
        # self._getints(self.tk.call(self._w, 'selection', 'get', first, last))
        # or we get a TypeError in that case
        sel = self.tk.call(self._w, 'selection', 'get', first, last)
        if isinstance(sel, int):
            return (sel, )
        else:
            return self._getints(sel)

    def selection_includes(self, itemDesc):
        '''Returns True if the item described by itemDesc is currently
        selected, False if it isn't.'''
        return self._getboolean(self.tk.call(
                                self._w, 'selection', 'includes', itemDesc))

    def selection_modify(self, select=(), deselect=()):
        '''Both arguments SELECT and DESELECT must be the string ALL or a
        possibly-empty list of item descriptions. Any unselected items in
        SELECT are added to the selection, and any selected items in DESELECT
        are removed from the selection (except for those items which are also
        in SELECT). A <Selection> event is generated if any items were
        selected or deselected.'''
        self.tk.call(self._w, 'selection', 'modify',
                     select or (), deselect or ())

    def style_cget(self, style, option):
        '''This command returns the current value of the option named OPTION
        associated with the style given by STYLE. OPTION may have any of the
        values accepted by the style_configure() widget command.'''
        return self.tk.call(self._w, 'style', 'cget', style, option)

    def style_configure(self, style, cnf=None, **kw):
        '''This command is similar to the configure() widget command except
        that it modifies options associated with the style given by STYLE
        instead of modifying options for the overall treectrl widget. The
        options of a style have effect on all elements managed by the style.
        The following options are supported:
        -buttony offset
            Specifies the distance from the top of the item that the
            expand/collapse button should be drawn. If offset is an empty
            string (the default) then the button is centered vertically in
            the item. The value may have any of the forms acceptable to
            Tk_GetPixels. This option only has effect when the style is
            set in an item in the tree column.
        -orient varName
            This option specifies which orientation should be used when
            laying out the elements associated with this style.
            Must be either horizontal (the default) or vertical or an
            abbreviation of one of these.'''
        return self._configure(('style', 'configure', style), cnf, kw)
    style_config = style_configure

    def style_create(self, name=None, *args, **kw):
        '''Create a new style in pathName with name STYLE. After STYLE there
        may be any number of option-value pairs, each of which sets one of the
        configuration options for the style. These same option-value pairs may
        be used in style_configure() widget commands to change the style's
        configuration. Returns the name of the new style.'''
        if name is None:
            Treectrl._last_style += 1
            name = 'pystyle' + str(Treectrl._last_style)
        return self._create('style', (name, args), kw)
    create_style = style_create

    def style_delete(self, style):
        '''Deletes each of the named STYLEs. If a style is deleted while it is
        still used to display one or more items, it is also removed from the
        style list of these items.'''
        self.tk.call(self._w, 'style', 'delete', style)
    delete_style = style_delete

    def style_elements(self, style, *elementList):
        '''Specifies the elements which should be layed out by this style.
        Each element of ELEMENTLIST must be the name of an element created by
        the widget command element_create(). Duplicate names in ELEMENTLIST
        are ignored. An element which was specified in a former call of this
        command for STYLE but is not included in ELEMENTLIST, will be deleted
        from the elements layed out by STYLE. If the ELEMENTLIST argument is
        not specified, a list is returned containing the currently defined
        elements of STYLE.'''
        if elementList:
            return self.tk.call(self._w, 'style', 'elements',
                                style, elementList) or None
        return self.tk.splitlist(self.tk.call(
                                    self._w, 'style', 'elements', style))

    def style_layout(self, style, element, cnf=None, **kw):
        '''This command is similar to the configure() widget command except
        that it modifies options used by STYLE for laying out ELEMENT instead
        of modifying options for the overall treectrl widget. The options of a
        layout have effect on exactly the one element ELEMENT managed by STYLE.
        The following options are supported:
        -detach boolean
            Specifies whether the element should be positioned by itself,
            i.e. independent from the other elements.
        -expand flags
            This option allows the external padding around the element to
            increase when a style has more screen space than it needs. Flags
            is a string that contains zero or more of the characters n, s, w
            or e. Each letter refers to the padding on the top, bottom, left,
            or right that should be allowed to increase. This option is
            typically used to justify an element.
        -iexpand flags
            This option allows the internal padding of the element and the
            display area of the element to increase when a style has more
            screen space than it needs. Flags is a string that contains zero
            or more of the characters x, y, n, s, w or e. For n, s, w and e,
            each letter refers to the padding on the top, bottom, left, or
            right that should be allowed to increase. For x and y, each letter
            refers to the horizontal and vertical screen space the element can
            display itself in (i.e., the space between the padding). Note that
            if the -union option is specified for this element, then the x and
            y flags have no effect, since the size of an element with -union
            layout is determined by the elements it surrounds.
        -indent boolean
            Specifies whether the element should be positioned to the right of
            the button/line area in the tree column.
            This option is ignored unless the -detach option is true.
        -ipadx amount
        -ipady amount
            Amount specifies how much internal padding to leave on the left
            and right (for -ipadx) or top and bottom (for -ipady) side of the
            element. Amount may be a list of two values to specify padding for
            the two sides separately, it defaults to 0.
        -minheight pixels
        -height pixels
        -maxheight pixels
            Specifies the minimum, fixed, and maximum height of the element.
        -minwidth pixels
        -width pixels
        -maxwidth pixels
            Specifies the minimum, fixed, and maximum width of the element.
        -padx amount
        -pady amount
            Amount specifies how much external padding to leave on the left
            and right (for -padx) or top and bottom (for -pady) side of the
            element. Amount may be a list of two values to specify padding
            for the two sides separately, it defaults to 0.
        -squeeze flags
            This option allows the display area of an element to decrease when
            a style has less space than it needs. Flags is a string that
            contains zero or more of the characters x or y. x allows display
            area to decrease horizontally, y allows display area to decrease
            vertically. This option is typically used for text elements and
            will cause the text element to display an ellipsis (...) and/or
            wrap lines.
        -sticky flags
            This option controls how the actual display information
            (image, text, etc) of an element is positioned (or stretched)
            within its display area. Flags is a string that contains zero
            or more of the characters n, s, w or e. Each letter refers to
            the top, bottom, left or right side of the display area that
            the display information should "stick" to.
        -union elementList
            Specifies a list of other elements which this element will
            surround. The size of an element with -union layout is determined
            by the size and position of the elements in elementList. The
            -ipadx and -ipady options in this case refer to the distance of
            the edges of the display area of this element from those elements
            it surrounds. This option is typically used to display a
            selection rectangle around a piece of text.
            Since treectrl-2.3 it is ok to include an element with -union
            layout in another element's -union list.
            Previously, nesting -union elements had undefined behavior.'''
        return self._configure(('style', 'layout', style, element), cnf, kw)

    def style_names(self):
        '''Returns a list containing the names of all existing styles.'''
        return self.tk.splitlist(self.tk.call(self._w, 'style', 'names'))

    def theme_platform(self):
        '''Returns the API used to draw themed parts of the treectrl.
        On Mac OS X the result is always aqua. On MS Windows the result is
        visualstyles if the uxtheme.dll was loaded and visual themes are
        in use, otherwise X11 is returned to indicate the Tk Xlib calls are
        drawing the themed parts. On Unix systems the result is gtk if the
        Gtk+ version of treectrl was built, otherwise X11 is returned.'''
        return self.tk.call(self._w, 'theme', 'platform')

    def theme_setwindowtheme(self, appname):
        '''The command is available on MS Windows only. If appname is
        "Explorer" then the item buttons look like those in the Explorer file
        browser (disclosure triangles under Windows Vista/7). If appname is an
        empty string then the buttons revert to their default appearance
        according to the system's current visual style.'''
        return self.tk.call(self._w, 'theme', 'setwindowtheme', appname)

    def xview(self, *what):
        """Query and change horizontal position of the view."""
        if not what:
            return self._getdoubles(self.tk.call(self._w, 'xview'))
        self.tk.call((self._w, 'xview') + what)

    def xview_moveto(self, fraction):
        """Adjust the view in the window so that FRACTION of the
        total width of the entry is off-screen to the left."""
        self.tk.call(self._w, 'xview', 'moveto', fraction)

    def xview_scroll(self, number, what):
        """Shift the x-view according to NUMBER which is measured in
        "units" or "pages" (WHAT)."""
        self.tk.call(self._w, 'xview', 'scroll', number, what)

    def yview(self, *what):
        """Query and change vertical position of the view."""
        if not what:
            return self._getdoubles(self.tk.call(self._w, 'yview'))
        self.tk.call((self._w, 'yview') + what)

    def yview_moveto(self, fraction):
        """Adjust the view in the window so that FRACTION of the
        total width of the entry is off-screen to the top."""
        self.tk.call(self._w, 'yview', 'moveto', fraction)

    def yview_scroll(self, number, what):
        """Shift the y-view according to NUMBER which is measured in
        "units" or "pages" (WHAT)."""
        self.tk.call(self._w, 'yview', 'scroll', number, what)

    #########################################################################
    #         library commands from FileListBindings.tcl                    #
    #########################################################################

    def filelist_emulate_win7(self, win7=None):
        '''Query or change the flag indicating that Windows 7 behavior should
        be used. If called without arguments returns True or False depending
        on the current state. If called with a boolean value as argument
        changes the behavior according to the given value.'''
        if win7 is None:
            return self._getboolean(
                    self.tk.call('TreeCtrl::FileListEmulateWin7', self._w))
        self.tk.call('TreeCtrl::FileListEmulateWin7', self._w, win7)

    def is_sensitive(self, x, y):
        '''Returns True if the given window coordinates are over an element
        that should respond to mouse clicks. The list of elements that
        respond to mouse clicks is set by calling set_sensitive().'''
        return self._getboolean(
                    self.tk.call('TreeCtrl::IsSensitive', self._w, x, y))

    def is_sensitive_marquee(self, x, y):
        '''Returns True if the given window coordinates are over an element
        that should respond to the marquee. The list of elements that respond
        to the marquee is set by calling set_sensitive_marquee(), or if that
        list is empty then the same list passed to set_sensitive().'''
        return self._getboolean(
                self.tk.call('TreeCtrl::IsSensitiveMarquee', self._w, x, y))

    def set_dragimage(self, *args):
        '''This command may be used to define elements that should be drawn
        as drag images during drag operations.
        ARGS must be one or more tuples of the form (COLUMN, STYLE, ELEMENT)
        that define the elements that are supposed to be drawn.
        For this to take effect, at least calls to
        self.bindtags(('TreeCtrlFileList',)) and self.set_sensitive(*args)
        must be made before.'''
        self.tk.call('TreeCtrl::SetDragImage', self._w, (args))

    def set_editable(self, *args):
        '''This command may be used to define text cells that should be
        user-editable. ARGS must be one or more tuples of the form
        (COLUMN, STYLE, ELEMENT) that define the text elements that are
        supposed to be editable. For this to take effect, at least calls to
        self.bindtags(('TreeCtrlFileList',)) and self.set_sensitive(*args)
        must be made before.'''
        self.tk.call('TreeCtrl::SetEditable', self._w, (args))

    def set_selected_items_sensitive(self, sensitive):
        '''Specifies whether or not entire items are sensitive to mouse clicks
        when they are already selected. SENSITIVE must be a boolean value.'''
        # does not return anything and does not seem to have any
        # effect either
        self.tk.call(
                'TreeCtrl::SetSelectedItemsSensitive', self._w, sensitive)

    def set_sensitive(self, *args):
        '''Defines elements that are supposed to respond to mouse events
        after file list bindings have been applied to the widget with
        bindtags(('TreeCtrlFileList',)). ARGS must be one or more tuples of
        the form (COLUMN, STYLE, ELEMENT) that define the desired elements.'''
        self.tk.call('TreeCtrl::SetSensitive', self._w, (args))

    def set_sensitive_marquee(self, *args):
        '''Just like set_sensitive() but indicates which elements respond to
        the selection rectangle. Typically this is the same as the elements
        passed to set_sensitive() with the addition of the selection rectangle
        elements.'''
        self.tk.call('TreeCtrl::SetSensitiveMarquee', self._w, (args))

